<template>
  <div class="complex-table">
    <div v-if="$slots.header || header" class="complex-table__header">
      <slot name="header">{{ header }}</slot>
    </div>

    <div class="complex-table__toolbar">
      <div class="search-wrapper">
        <div v-if="searchConfig" class="w-50">
          <el-input
            v-model="searchKW"
            :placeholder="$t('commons.button.search')"
            suffix-icon="Search"
            clearable
            @change="search(true)"
          />
        </div>
        <slot name="toolbar" />
      </div>
    </div>

    <div class="complex-table__body">
      <fu-table
        :empty-text="$t('commons.table.empty_text')"
        v-bind="$attrs"
        :columns="columns"
        :local-key="localKey"
        @selection-change="handleSelectionChange"
      >
        <slot />
      </fu-table>
    </div>

    <div v-if="$slots.pagination || page" class="complex-table__pagination">
      <slot name="pagination">
        <fu-table-pagination
          v-model:current-page="pageNum"
          v-model:page-size="pageSize"
          v-bind="page"
          @current-change="search"
          @size-change="search(true)"
        />
      </slot>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, ref } from "vue";

type Prop = {
  columns?: any[];
  localKey?: string;
  header?: string;
  searchConfig?: {
    keywords: string;
  };
  page?: {
    currentPage: number;
    pageSize: number;
  };
  selects?: any[];
};

const props = defineProps<Prop>();
const emit = defineEmits([
  "search",
  "update:selects",
  "update:page",
  "update:searchConfig"
]);

const pageShow = ref(false);

const searchKW = computed({
  get() {
    return props.searchConfig?.keywords || "";
  },
  set(val) {
    emit("update:searchConfig", { ...props.searchConfig, keywords: val });
  }
});

const pageNum = computed({
  get() {
    return props.page?.currentPage || 1;
  },
  set(val) {
    emit("update:page", { ...props.page, currentPage: val });
  }
});

const pageSize = computed({
  get() {
    return props.page?.pageSize || 10;
  },
  set(val) {
    emit("update:page", { ...props.page, pageSize: val });
  }
});

const search = resetPage => {
  emit("search", resetPage);
};
const handleSelectionChange = val => {
  emit("update:selects", val);
};
</script>

<style lang="scss">
@import url("@/style/common/mixins.scss");
@import url("@/style/common/variables.scss");

.complex-table {
  .complex-table__header {
    // @include flex-row(flex-start, center);
    line-height: 60px;
    font-size: 18px;
    margin-bottom: 10px;
  }

  .complex-table__toolbar {
    // @include flex-row(flex-end, center);
    margin-bottom: 10px;

    .search-wrapper {
      width: 100%;
      display: flex;
      justify-content: flex-end;
    }
  }

  .complex-table__pagination {
    margin-top: 20px;
    // @include flex-row(flex-end);
  }
}
</style>
